package com.zdkj.subway.check.controller.subwayRat.TVMRevenueVarianceAudit.TvmChaYiDXC;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.check.controller.CommonController;
import com.zdkj.subway.check.entity.Page;
import com.zdkj.subway.check.entity.SwAuTvmSingleAssist;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.mapper.SwAuTvmSingleAssistMapper;
import com.zdkj.subway.check.mapper.SysUserMapper;
import com.zdkj.subway.check.result.Result;
import com.zdkj.subway.check.service.SwAuTvmSingleAssistService;
import com.zdkj.subway.check.service.SwAuTvmSingleAssistToService;
import com.zdkj.subway.check.util.UserInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 数据协查管理-TVM系统差异协查-TVM单台设备差异
 * TVM票款差异协查-单台设备 SW_AU_TVM_SINGLE_ASSIST
 */
@Slf4j
@RestController
@RequestMapping("/checkNew")
public class SwAuTvmSingleAssistCtrl {

    private static final Logger LOGGER = LoggerFactory.getLogger(SwAuTvmSingleAssist.class);

    @Resource
    private SwAuTvmSingleAssistService swAuTvmSingleAssistService;
    @Autowired
    private SwAuTvmSingleAssistMapper swAuTvmSingleAssistMapper;
    @Resource
    private SwAuTvmSingleAssistToService swAuTvmSingleAssistToService;
    @Autowired
    private CommonController commonController;
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 导入
     *
     * @param
     * @return
     */
    @ApiOperation(value = "TVM单台设备协查导入", notes = "TVM单台设备协查导入")
    @SysLog("TVM单台设备协查导入")
    @PostMapping({"/importTvmSingle"})
    public R importTVM(@RequestParam("file") final MultipartFile file) throws Exception {
        final File excelFile = MultipartFileToFile.multipartFileToFile(file);
        return R.ok((Object)this.swAuTvmSingleAssistService.importTvmSingle(excelFile));
    }

    /**
     * 导出
     * @param
     * @return
     */
    @ApiOperation(value = "TVM单台设备导出", notes = "TVM单台设备导出")
    @GetMapping({"/exportTvmSingle"})
    @SysLog("TVM单台设备导出")
    public void export(String ids, String tag, SwAuTvmSingleAssist swAuTvmSingleAssist, HttpServletResponse response) throws ParseException {
        swAuTvmSingleAssistService.export(ids,tag,swAuTvmSingleAssist,response);
    }

        /**
         * 车站票款差异通知 列表
         * @param param
         * @return
         */
    @RequestMapping("/getSwAuTvmSingleAssistList")
    @ApiOperation(value = "车站票款差异通知 列表", notes = "车站票款差异通知 列表")
    public Page getSwAuTvmSingleAssistList(Page page, @RequestParam Map<String,String> param){
        SwAuTvmSingleAssist swAuTvmSingleAssist = new SwAuTvmSingleAssist();
        /*String lineCode = String.valueOf(param.get("lineCode"));
        if(StringUtils.isEmpty(lineCode)) {
            List<String> lineCodeList = new ArrayList<>();
            PigxUser user = SecurityUtils.getUser();
            Map<String, Object> p1 = new HashMap<>();
            p1.put("user_code", user.getUserCode());
            List<SysUser> sysUsers = sysUserMapper.selectByMap(p1);
            SysUser sysUser = sysUsers.get(0);
            String managementLineStation = sysUser.getManagementLineStation();
            if (!StringUtils.isEmpty(managementLineStation)) {
                JSONArray managementLineStations = JSONArray.parseArray(managementLineStation);
                for (int i = 0; i < managementLineStations.size(); i++) {
                    JSONObject jsonObject1 = managementLineStations.getJSONObject(i);
                    //存在多条线路
                    lineCodeList.add(jsonObject1.getString("line"));
                }
                swAuTvmSingleAssist.setLineCode(org.apache.commons.lang3.StringUtils.join(lineCodeList,","));
            }else {
                //不管辖线路
                swAuTvmSingleAssist.setLineCode(sysUser.getLineCode());
            }
        }*/
        List<Map<String, Object>> swAuTvmSingleAssistList = swAuTvmSingleAssistMapper.getSwAuTvmSingleAssistList(param);
        /*JSONObject resultJson = new JSONObject();
        resultJson.put("list", swAuTvmSingleAssistList);
        PageInfo<SwAuTvmSingleAssist> swAuTvmSingleAssistPageInfo = new PageInfo(swAuTvmSingleAssistList);
        resultJson.put("pageInfo", swAuTvmSingleAssistPageInfo);
        return new Result(ResultDetailMsg.OK, resultJson);*/
        page.setData(swAuTvmSingleAssistList,true);
        return page;
    }

    /**
     * 车站票款差异通知 客运列表
     * @param param
     * @return
     */
    @RequestMapping("/getSwAuTvmSingleAssistListKY")
    @ApiOperation(value = "车站票款差异通知 客运列表", notes = "车站票款差异通知 客运列表")
    public Page getSwAuTvmSingleAssistListKY(Page page, @RequestParam Map<String,String> param){
        /*if(StringUtils.isEmpty(swAuTvmSingleAssist.getLineCode())) {
            String lineCode = "";
            PigxUser user = SecurityUtils.getUser();
            Map<String, Object> p1 = new HashMap<>();
            p1.put("user_code", user.getUserCode());
            List<SysUser> sysUsers = sysUserMapper.selectByMap(p1);
            SysUser sysUser = sysUsers.get(0);
            String managementLineStation = sysUser.getManagementLineStation();
            if (!StringUtils.isEmpty(managementLineStation)) {
                JSONArray managementLineStations = JSONArray.parseArray(managementLineStation);
                for (int i = 0; i < managementLineStations.size(); i++) {
                    JSONObject jsonObject1 = managementLineStations.getJSONObject(i);
                    lineCode = jsonObject1.getString("line");
                }
                swAuTvmSingleAssist.setLineCode(lineCode);
            }else {
                //不管辖线路
                swAuTvmSingleAssist.setLineCode(sysUser.getLineCode());
                swAuTvmSingleAssist.setStationCode(sysUser.getStationCode());
            }
        }*/
        /*JSONObject resultJson = new JSONObject();
        resultJson.put("list", swAuTvmSingleAssistList);
        PageInfo<SwAuTvmSingleAssist> swAuTvmSingleAssistPageInfo = new PageInfo(swAuTvmSingleAssistList);
        resultJson.put("pageInfo", swAuTvmSingleAssistPageInfo);
        return new Result(ResultDetailMsg.OK, resultJson);*/
        PigxUser user = SecurityUtils.getUser();
        String lineCode = user.getLineCode();
        String stationCode = user.getStationCode();
        param.put("lineCode",lineCode);
        param.put("stationCode",stationCode);//只查本车站
        List<Map<String, Object>> swAuTvmSingleAssistList = swAuTvmSingleAssistMapper.getSwAuTvmSingleAssistList(param);
        page.setData(swAuTvmSingleAssistList,true);
        return page;
    }

    /**
     * 车站票款差异通知 其他运营中心列表
     * @param swAuTvmSingleAssist
     * @return
     */
    @RequestMapping("/getSwAuTvmSingleAssistLisCenter")
    @ApiOperation(value = "车站票款差异通知 其他运营中心列表", notes = "车站票款差异通知 其他运营中心列表")
    public Result getSwAuTvmSingleAssistLisCenter(@RequestBody SwAuTvmSingleAssist swAuTvmSingleAssist){
        List<Map<String, Object>> swAuTvmSingleAssistList = swAuTvmSingleAssistMapper.getSwAuTvmSingleAssistList(swAuTvmSingleAssist);
        JSONObject resultJson = new JSONObject();
        resultJson.put("list", swAuTvmSingleAssistList);
        PageInfo<SwAuTvmSingleAssist> swAuTvmSingleAssistPageInfo = new PageInfo(swAuTvmSingleAssistList);
        resultJson.put("pageInfo", swAuTvmSingleAssistPageInfo);
        return new Result(ResultDetailMsg.OK, resultJson);
    }

    /**
     * 车站票款差异通知 单独查询
     * @param jsonObject
     * @return
     */
    @RequestMapping("/getSwAuTvmSingleAssist")
    @ApiOperation(value = "车站票款差异通知 单独查询", notes = "车站票款差异通知 单独查询")
    public Result getSwAuTvmSingleAssist(@RequestBody JSONObject jsonObject){
        return swAuTvmSingleAssistService.getSwAuTvmSingleAssist(jsonObject);
    }

    /**
     * 车站票款差异通知 修改 机电
     * @param jsonObject
     * @return
     */
    @RequestMapping("/updateSwAuTvmSingleAssistToStatus")
    @ApiOperation(value = "车站票款差异通知 修改 机电", notes = "车站票款差异通知 修改 机电")
    @Transactional(rollbackFor = Exception.class)
    public Result updateSwAuTvmSingleAssistToStatus(@RequestBody JSONObject jsonObject){
        try{
            if(null != jsonObject.getJSONArray("ids")){
                JSONArray ids = jsonObject.getJSONArray("ids");
                for(Object idObj: ids){
                    Integer id = Integer.valueOf(idObj.toString());
                    SwAuTvmSingleAssist swAuTvmSingleAssist = new SwAuTvmSingleAssist();
                    swAuTvmSingleAssist.setId(id);
                    swAuTvmSingleAssist.setReplyStatus("1");
                    swAuTvmSingleAssist.setAssistInvestStatus("3");//已协查
                    swAuTvmSingleAssist.setReplyTime(new Date());
                    swAuTvmSingleAssistMapper.updateById(swAuTvmSingleAssist);
                }
                Map param = JSONObject.parseObject(jsonObject.toString(),Map.class);
                commonController.innerBatch(param);
            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return new Result(ResultDetailMsg.OK);
    }

    /**
     * 车站票款差异通知 客运修改
     * @param jsonObject
     * @return
     */
    @RequestMapping("/updateSwAuTvmSingleAssistKYToStatus")
    @ApiOperation(value = "车站票款差异通知 客运修改", notes = "车站票款差异通知 客运修改")
    @Transactional(rollbackFor = Exception.class)
    public Result updateSwAuTvmSingleAssistKYToStatus(@RequestBody JSONObject jsonObject){
        try{
            if(null != jsonObject.getJSONArray("ids")){
                JSONArray ids = jsonObject.getJSONArray("ids");
                for(Object idObj: ids){
                    Integer id = Integer.valueOf(idObj.toString());
                    SwAuTvmSingleAssist swAuTvmSingleAssist = new SwAuTvmSingleAssist();
                    swAuTvmSingleAssist.setId(id);
                    swAuTvmSingleAssist.setKyReplyStatus("1");
                    swAuTvmSingleAssist.setKyAssistInvestStatus("3");//已协查
                    swAuTvmSingleAssist.setKyReplyTime(new Date());
                    swAuTvmSingleAssistMapper.updateById(swAuTvmSingleAssist);
                }
                Map param = JSONObject.parseObject(jsonObject.toString(),Map.class);
                commonController.innerBatch(param);
            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return new Result(ResultDetailMsg.OK);
    }
    /**
     * 车站票款差异通知 修改
     * @param jsonObject
     * @return
     */
    @RequestMapping("/updateSwAuTvmSingleAssist")
    @ApiOperation(value = "车站票款差异通知 修改", notes = "车站票款差异通知 修改")
    public Result updateSwAuTvmSingleAssist(@RequestBody JSONObject jsonObject){
        if(null != jsonObject.getInteger("id")){
            Integer id = jsonObject.getInteger("id");
            SwAuTvmSingleAssist swAuTvmSingleAssist = new SwAuTvmSingleAssist();
            swAuTvmSingleAssist.setId(id);
            String replyReason = jsonObject.getString("replyReason");
            String replyContent = jsonObject.getString("replyContent");
            BigDecimal replyDiffMoney = jsonObject.getBigDecimal("replyDiffMoney");
            BigDecimal replyRechargeMoney = jsonObject.getBigDecimal("replyRechargeMoney");
            BigDecimal replySaleMoney = jsonObject.getBigDecimal("replySaleMoney");
            BigDecimal replyErrorReturnMoney = jsonObject.getBigDecimal("replyErrorReturnMoney");
            BigDecimal replyTotal = jsonObject.getBigDecimal("replyTotal");
            swAuTvmSingleAssist.setReplyDiffMoney(replyDiffMoney);
            swAuTvmSingleAssist.setReplyRechargeMoney(replyRechargeMoney);
            swAuTvmSingleAssist.setReplySaleMoney(replySaleMoney);
            swAuTvmSingleAssist.setReplyErrorReturnMoney(replyErrorReturnMoney);
            swAuTvmSingleAssist.setReplyTotal(replyTotal);
            swAuTvmSingleAssist.setReplyReason(replyReason);
            swAuTvmSingleAssist.setReplyContent(replyContent);
            swAuTvmSingleAssist.setOperatorId(UserInfo.getId());
            swAuTvmSingleAssist.setOperatorCode(UserInfo.getUserCode());
            this.swAuTvmSingleAssistMapper.updateById(swAuTvmSingleAssist);
        }
        return new Result(ResultDetailMsg.OK);
    }
    /**
     * 车站票款差异通知 客运修改
     * @param jsonObject
     * @return
     */
    @RequestMapping("/updateSwAuTvmSingleAssistKY")
    @ApiOperation(value = "车站票款差异通知 客运修改", notes = "车站票款差异通知 客运修改")
    public Result updateSwAuTvmSingleAssistKY(@RequestBody JSONObject jsonObject){
        PigxUser user = SecurityUtils.getUser();
        if(null != jsonObject.getInteger("id")){
            Integer id = jsonObject.getInteger("id");
            SwAuTvmSingleAssist swAuTvmSingleAssist = new SwAuTvmSingleAssist();
            swAuTvmSingleAssist.setId(id);
            String kyReplyReason = jsonObject.getString("kyReplyReason");
            String kyReplyDetail = jsonObject.getString("kyReplyDetail");
            swAuTvmSingleAssist.setKyReplyReason(kyReplyReason);
            swAuTvmSingleAssist.setKyReplyDetail(kyReplyDetail);
            swAuTvmSingleAssist.setKyReplyCode(user.getUserCode());
            swAuTvmSingleAssist.setKyReplyName(user.getNikeName());
            this.swAuTvmSingleAssistMapper.updateById(swAuTvmSingleAssist);
        }
        return new Result(ResultDetailMsg.OK);
    }

    /**
     * 撤回TVM单台设备票款差异 撤回
     * @param
     * @return
     */
    @RequestMapping("/revokeTvmDanTai")
    @ApiOperation(value = "撤回TVM单台设备票款差异 撤回", notes = "撤回TVM单台设备票款差异 撤回")
    public R revokeTvmDanTai(String ids) {
        List<SwAuTvmSingleAssist> singleAssists = swAuTvmSingleAssistMapper.selectBatchIds(Arrays.asList(ids.split(",")));
        if(CollectionUtil.isNotEmpty(singleAssists)){
            for(SwAuTvmSingleAssist singleAssist:singleAssists){
                if("1".equals(singleAssist.getReplaceStatus())){
                    return R.failed("已经替换的数据不能撤回！");
                }
                SwAuTvmSingleAssist s=new SwAuTvmSingleAssist();
                s.setId(singleAssist.getId());
                s.setReplyStatus("0");//机电回馈状态改为0，未回馈
                s.setAssistInvestStatus("2");//协查状态改为2，待协查
                swAuTvmSingleAssistMapper.updateById(s);
            }
        }
        return R.ok();
    }
}
